package ee122Networking;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.sql.Timestamp;


public class ServerReceiverThread extends Thread {
	static int _PORT_NUMBER = 4500;
	protected DatagramSocket socket = null;

	public int numPacketsReceived;
	
	public ServerReceiverThread () {
		numPacketsReceived=0;
		try {
			
			socket = new DatagramSocket(_PORT_NUMBER);
			
		} catch (SocketException e1) {
			System.out.println("Socket could not be opened on port " + _PORT_NUMBER);
			e1.printStackTrace();
		} catch (SecurityException e2) {
			System.out.println("Security manager did not allow the conenction to be established");
			e2.printStackTrace();
		}
		System.out.println("Server started. Listening on port " + socket.getLocalPort());
	}
	
	
	public void run(){
		
		
		byte[] buf = new byte[128]; //TODO: get rid of hardcoded number
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		
		boolean listening = true;
		
		while (listening){
					
			try {
				if (socket!=null)
					socket.receive(packet);
					buf = packet.getData();
					processData(buf, packet.getOffset(), packet.getLength());
					
					if(numPacketsReceived > 50){
						listening = false;
					}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		socket.close();
		
	
	}

	private void processData(byte[] buf, int offset, int length) {
		numPacketsReceived++;
		long timestamp = 0;
		byte[] timestampdata = new byte[8];
		System.arraycopy(buf, buf.length-8, timestampdata, 0, 8);
		ByteArrayInputStream bis = new ByteArrayInputStream(timestampdata);
		DataInputStream dis = new DataInputStream(bis);
		try {
			timestamp = dis.readLong();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Received " + numPacketsReceived + " packets");
		System.out.println("This packet's sequence number is "+buf[0]+ " sent at " + new Timestamp(timestamp));
		
	}	
	
	
}
